package com.ihrm.employee.controller;

import com.github.pagehelper.PageInfo;
import com.ihrm.common.controller.BaseController;
import com.ihrm.common.entity.Result;
import com.ihrm.common.entity.ResultCode;
import com.ihrm.common.poi.ExcelExportUtil;
import com.ihrm.common.utils.BeanMapUtils;
import com.ihrm.common.utils.DownloadUtils;
import com.ihrm.domain.employee.*;
import com.ihrm.domain.employee.response.EmployeeReportResult;
import com.ihrm.domain.system.User;
import com.ihrm.employee.client.SystemFeignClient;
import com.ihrm.employee.service.api.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;


@RestController
@CrossOrigin
@RequestMapping("/employees")
public class EmployeeController extends BaseController {

    @Autowired
    private UserCompanyPersonalService userCompanyPersonalService;
    @Autowired
    private UserCompanyJobsService userCompanyJobsService;
    @Autowired
    private ResignationService resignationService;
    @Autowired
    private TransferPositionService transferPositionService;
    @Autowired
    private PositiveService positiveService;
    @Autowired
    private ArchiveService archiveService;
    @Autowired
    private SystemFeignClient systemFeignClient;


    /**
     * 员工个人信息更新或保存
     */
    @RequestMapping(value = "/{id}/personalInfo", method = RequestMethod.PUT)
    public Result updatePersonalInfo(@PathVariable(name = "id") String uid, @RequestBody Map map) throws Exception {
        UserCompanyPersonal sourceInfo = BeanMapUtils.mapToBean(map, UserCompanyPersonal.class);
        UserCompanyPersonal byId = userCompanyPersonalService.findById(uid);
        if (byId != null) {
            sourceInfo.setCompanyId(super.companyId);
            userCompanyPersonalService.update(sourceInfo);
        } else {
            sourceInfo.setUserId(uid);
            sourceInfo.setCompanyId(super.companyId);
            userCompanyPersonalService.insert(sourceInfo);
        }
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 员工个人信息读取
     */
    @RequestMapping(value = "/{id}/personalInfo", method = RequestMethod.GET)
    public Result findPersonalInfo(@PathVariable(name = "id") String uid) throws Exception {
        UserCompanyPersonal info = userCompanyPersonalService.findById(uid);

        if (info == null) {
            info = new UserCompanyPersonal();
            info.setUserId(uid);
        }
        return new Result(ResultCode.SUCCESS, info);
    }

    /**
     * 员工个人信息删除
     */
    @RequestMapping(value = "/{id}/personalInfo", method = RequestMethod.DELETE)
    public Result deletePersonalInfo(@PathVariable(name = "id") String uid) {
        userCompanyPersonalService.delete(uid);
        return new Result(ResultCode.SUCCESS);
    }


    /**
     * 员工岗位信息更新或保存
     */
    @RequestMapping(value = "/{id}/jobs", method = RequestMethod.PUT)
    public Result updateJobsInfo(@PathVariable(name = "id") String uid, @RequestBody UserCompanyJobs sourceInfo) throws Exception {
        UserCompanyJobs byId = userCompanyJobsService.findById(uid);
        if (byId != null) {
            sourceInfo.setCompanyId(super.companyId);
            userCompanyJobsService.update(sourceInfo);
        } else {
            sourceInfo.setUserId(uid);
            sourceInfo.setCompanyId(super.companyId);
            userCompanyJobsService.insert(sourceInfo);
        }
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 员工岗位信息读取
     */
    @RequestMapping(value = "/{id}/jobs", method = RequestMethod.GET)
    public Result findJobsInfo(@PathVariable(name = "id") String uid) throws Exception {
        UserCompanyJobs info = userCompanyJobsService.findById(uid);
        if (info == null) {
            info = new UserCompanyJobs();
            info.setUserId(uid);
            info.setCompanyId(companyId);
            userCompanyJobsService.insert(info);
        }
        EmployeePositive byId = positiveService.findById(uid);
        if (byId != null) {
            if (byId.getEstatus() == 1) {
                info.setStateOfCorrection("转正申请中");
            } else if (byId.getEstatus() == 2) {
                info.setStateOfCorrection("已转正");
            }
            info.setCorrectionEvaluation(byId.getCorrectionEvaluation());
        } else {
            info.setStateOfCorrection("未转正");
            info.setCorrectionEvaluation("");
        }
        userCompanyJobsService.update(info);
        return new Result(ResultCode.SUCCESS, info);
    }


    /**
     * 员工岗位信息删除
     */
    @RequestMapping(value = "/{id}/jobs", method = RequestMethod.DELETE)
    public Result deleteJobsInfo(@PathVariable(name = "id") String uid) {
        userCompanyJobsService.delete(uid);
        return new Result(ResultCode.SUCCESS);
    }


    /**
     * 离职表单保存或更新
     */
    @RequestMapping(value = "/{id}/leave", method = RequestMethod.PUT)
    public Result updateLeave(@PathVariable(name = "id") String uid, @RequestBody EmployeeResignation resignation) throws Exception {
        EmployeeResignation byId = resignationService.findById(uid);
        User user = systemFeignClient.findUserById(uid);
        if (byId != null) {
            resignationService.update(resignation);
        } else {
            resignation.setUserId(uid);
            resignationService.insert(resignation);
        }
        user.setInServiceStatus(2);
        systemFeignClient.update(user);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 离职表单读取
     */
    @RequestMapping(value = "/{id}/leave", method = RequestMethod.GET)
    public Result findLeave(@PathVariable(name = "id") String uid) throws Exception {
        EmployeeResignation resignation = resignationService.findById(uid);
        if (resignation == null) {
            resignation = new EmployeeResignation();
            resignation.setUserId(uid);
        }
        return new Result(ResultCode.SUCCESS, resignation);
    }

    /**
     * 导入员工
     */
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    public Result importDatas(@RequestParam(name = "file") MultipartFile attachment) throws Exception {
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 调岗表单保存或更新
     */
    @RequestMapping(value = "/{id}/transferPosition", method = RequestMethod.PUT)
    public Result updateTransferPosition(@PathVariable(name = "id") String uid, @RequestBody EmployeeTransferPosition transferPosition) throws Exception {
        EmployeeTransferPosition byId = transferPositionService.findById(uid);
        transferPosition.setUserId(uid);
        if (byId != null) {
            transferPositionService.update(transferPosition);
        } else {
            transferPosition.setUserId(uid);
            transferPositionService.insert(transferPosition);
        }
        UserCompanyJobs userCompanyJobs = userCompanyJobsService.findById(uid);
        userCompanyJobs.setPost(transferPosition.getPost());
        userCompanyJobs.setReportName(transferPosition.getReportingObject());
        userCompanyJobs.setHrbp(transferPosition.getHrbp());
        userCompanyJobs.setCurrentContractStartTime(transferPosition.getCurrentContractStartTime());
        userCompanyJobs.setClosingTimeOfCurrentContract(transferPosition.getClosingTimeOfCurrentContract());
        userCompanyJobs.setInitialContractStartTime(transferPosition.getInitialContractStartTime());
        userCompanyJobs.setFirstContractTerminationTime(transferPosition.getFirstContractTerminationTime());
        userCompanyJobs.setContractPeriod(transferPosition.getContractPeriod());
        userCompanyJobs.setRenewalNumber(transferPosition.getRenewalNumber());
        userCompanyJobs.setRecommenderBusinessPeople(transferPosition.getRecommenderBusinessPeople());
        userCompanyJobs.setWorkingCity(transferPosition.getWorkingCity());
        userCompanyJobsService.update(userCompanyJobs);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 调岗表单读取
     */
    @RequestMapping(value = "/{id}/transferPosition", method = RequestMethod.GET)
    public Result findTransferPosition(@PathVariable(name = "id") String uid) throws Exception {
        UserCompanyJobs jobsInfo = userCompanyJobsService.findById(uid);
        if (jobsInfo == null) {
            jobsInfo = new UserCompanyJobs();
            jobsInfo.setUserId(uid);
        }
        return new Result(ResultCode.SUCCESS, jobsInfo);
    }

    /**
     * 转正表单保存或更新
     */
    @RequiresPermissions(value = "API-USER-POSITIVE")
    @RequestMapping(value = "/{id}/positive", method = RequestMethod.PUT)
    public Result updatePositive(@PathVariable(name = "id") String uid, @RequestBody EmployeePositive positive) {
        positive.setUserId(uid);
        EmployeePositive byId = positiveService.findById(uid);
        if (byId != null) {
            positiveService.update(positive);
        } else {
            positiveService.insert(positive);
        }
        Date dateOfCorrection = positive.getDateOfCorrection();
        User user = systemFeignClient.findUserById(uid);
        user.setCorrectionTime(dateOfCorrection);
        systemFeignClient.update(user);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 转正表单读取
     */
    @RequestMapping(value = "/{id}/positive", method = RequestMethod.GET)
    public Result findPositive(@PathVariable(name = "id") String uid) throws Exception {
        EmployeePositive positive = positiveService.findById(uid);
        if (positive == null) {
            positive = new EmployeePositive();
            positive.setUserId(uid);
        }
        return new Result(ResultCode.SUCCESS, positive);
    }

    /**
     * 历史归档详情列表
     */
    @RequestMapping(value = "/archives/{month}", method = RequestMethod.GET)
    public Result archives(@PathVariable(name = "month") String month, @RequestParam(name = "type") Integer type) throws Exception {
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 归档更新
     */
    @RequestMapping(value = "/archives/{month}", method = RequestMethod.PUT)
    public Result saveArchives(@PathVariable(name = "month") String month) throws Exception {
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 历史归档列表
     */
    @RequestMapping(value = "/archives", method = RequestMethod.GET)
    public Result findArchives(@RequestParam(name = "pagesize") Integer pagesize, @RequestParam(name = "page") Integer page, @RequestParam(name = "year") String year) throws Exception {
        Map map = new HashMap();
        map.put("year", year);
        map.put("companyId", companyId);
        PageInfo<EmployeeArchive> searchPage = archiveService.findSearch(map, page, pagesize);
        return new Result(ResultCode.SUCCESS, searchPage);
    }

//    /**
//     * 当月人事报表导出
//     * 参数month形式:2018-02
//     */
//    @RequestMapping(value = "/export/{month}", method = RequestMethod.GET)
//    public void export(@PathVariable(name = "month") String month) throws IOException {
//        //获取报表的数据
//        List<EmployeeReportResult> list = userCompanyPersonalService.findByReport(companyId, month);
//        //构造Excel
//        XSSFWorkbook wb = new XSSFWorkbook();
//        Sheet sheet = wb.createSheet();
//        String[] titles = "编号,姓名,手机,最高学历,国家地区,护照号,籍贯,生日,属相,入职时间,离职类型,离职原因,离职时间".split(",");
//        Row row = sheet.createRow(0);
//        int titleIndex = 0;
//        for (String title : titles) {
//            Cell cell = row.createCell(titleIndex++);
//            cell.setCellValue(title);
//        }
//        int rowIndex = 1;
//        Cell cell=null;
//        for (EmployeeReportResult employeeReportResult : list) {
//            row = sheet.createRow(rowIndex++);
//            // 编号,
//            cell = row.createCell(0);
//            cell.setCellValue(employeeReportResult.getUserId());
//            // 姓名,
//            cell = row.createCell(1);
//            cell.setCellValue(employeeReportResult.getUsername());
//            // 手机,
//            cell = row.createCell(2);
//            cell.setCellValue(employeeReportResult.getMobile());
//            // 最高学历,
//            cell = row.createCell(3);
//            cell.setCellValue(employeeReportResult.getTheHighestDegreeOfEducation());
//            // 国家地区,
//            cell = row.createCell(4);
//            cell.setCellValue(employeeReportResult.getNationalArea());
//            // 护照号,
//            cell = row.createCell(5);
//            cell.setCellValue(employeeReportResult.getPassportNo());
//            // 籍贯,
//            cell = row.createCell(6);
//            cell.setCellValue(employeeReportResult.getNativePlace());
//            // 生日,
//            cell = row.createCell(7);
//            cell.setCellValue(employeeReportResult.getBirthday());
//            // 属相,
//            cell = row.createCell(8);
//            cell.setCellValue(employeeReportResult.getZodiac());
//            // 入职时间,
//            cell = row.createCell(9);
//            cell.setCellValue(employeeReportResult.getTimeOfEntry());
//            // 离职类型,
//            cell = row.createCell(10);
//            cell.setCellValue(employeeReportResult.getTypeOfTurnover());
//            // 离职原因,
//            cell = row.createCell(11);
//            cell.setCellValue(employeeReportResult.getReasonsForLeaving());
//            // 离职时间
//            cell = row.createCell(12);
//            cell.setCellValue(employeeReportResult.getResignationTime());
//        }
//        //完成下载
//        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//        wb.write(byteArrayOutputStream);
//        new DownloadUtils().download(byteArrayOutputStream,response,month+"人事报表.xlsx");
//    }

    /**
     * 采用模板打印的形式打印当月人事报表
     * 参数month形式:2018-02
     */
    @RequestMapping(value = "/export/{month}", method = RequestMethod.GET)
    public void export(@PathVariable(name = "month") String month) throws Exception {
        //1.获取报表数据
        List<EmployeeReportResult> list = userCompanyPersonalService.findByReport(companyId, month);
        //2.加载模板
        Resource resource = new ClassPathResource("excel-template/hr-demo.xlsx");
        FileInputStream fis = new FileInputStream(resource.getFile());
        //3.通过工具类完成下载
        ExcelExportUtil excelExportUtil = new ExcelExportUtil(EmployeeReportResult.class, 2, 2);
        excelExportUtil.export(response,fis,list,month+"人事报表.xlsx");


        //3.根据模板创建工作簿
        Workbook wb = new XSSFWorkbook(fis);
        //4.读取工作表
        Sheet sheet = wb.getSheetAt(0);
        //5.抽取公共样式
        Row row = sheet.getRow(2);
        CellStyle[] styles = new CellStyle[row.getLastCellNum()];
        for (int i = 0; i < row.getLastCellNum(); i++) {
            Cell cell = row.getCell(i);
            styles[i] = cell.getCellStyle();
        }
        //6.构造单元格
        int rowIndex = 2;
        Cell cell = null;
            for (EmployeeReportResult employeeReportResult : list) {
                row = sheet.createRow(rowIndex++);
                // 编号,
                cell = row.createCell(0);
                cell.setCellValue(employeeReportResult.getUserId());
                cell.setCellStyle(styles[0]);
                // 姓名,
                cell = row.createCell(1);
                cell.setCellValue(employeeReportResult.getUsername());
                cell.setCellStyle(styles[1]);
                // 手机,
                cell = row.createCell(2);
                cell.setCellValue(employeeReportResult.getMobile());
                cell.setCellStyle(styles[2]);
                // 最高学历,
                cell = row.createCell(3);
                cell.setCellValue(employeeReportResult.getTheHighestDegreeOfEducation());
                cell.setCellStyle(styles[3]);
                // 国家地区,
                cell = row.createCell(4);
                cell.setCellValue(employeeReportResult.getNationalArea());
                cell.setCellStyle(styles[4]);
                // 护照号,
                cell = row.createCell(5);
                cell.setCellValue(employeeReportResult.getPassportNo());
                cell.setCellStyle(styles[5]);
                // 籍贯,
                cell = row.createCell(6);
                cell.setCellValue(employeeReportResult.getNativePlace());
                cell.setCellStyle(styles[6]);
                // 生日,
                cell = row.createCell(7);
                cell.setCellValue(employeeReportResult.getBirthday());
                cell.setCellStyle(styles[7]);
                // 属相,
                cell = row.createCell(8);
                cell.setCellValue(employeeReportResult.getZodiac());
                cell.setCellStyle(styles[8]);
                // 入职时间,
                cell = row.createCell(9);
                cell.setCellValue(employeeReportResult.getTimeOfEntry());
                cell.setCellStyle(styles[9]);
                // 离职类型,
                cell = row.createCell(10);
                cell.setCellValue(employeeReportResult.getTypeOfTurnover());
                cell.setCellStyle(styles[10]);
                // 离职原因,
                cell = row.createCell(11);
                cell.setCellValue(employeeReportResult.getReasonsForLeaving());
                cell.setCellStyle(styles[11]);
                // 离职时间
                cell = row.createCell(12);
                cell.setCellValue(employeeReportResult.getResignationTime());
                cell.setCellStyle(styles[12]);
            }
        //7.下载
        //3.完成下载
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        wb.write(os);
        new DownloadUtils().download(os, response, month + "人事报表.xlsx");
    }

}
